<?php
namespace Admin\Controller;

use Common\Controller\AdminbaseController;

class QuestionsController extends AdminbaseController{
    protected $ques_model;
    protected $term_relationships_model;
    protected $terms_model;
    
    protected $question_level;
    protected $question_opts;
    protected $question_types;
    protected $type_control;
    protected $option_count;
    
	public function _initialize() {
		parent::_initialize();
		$this->ques_model = D("Admin/Questions");
		$this->terms_model = D("Portal/QuesTerms");
		$this->term_relationships_model = D("Portal/QuesTermRelationships");
		
		$this->question_level=C('QUESTION_LEVEL');
		$this->question_types=C('QUESTION_TYPES');
		$this->question_opts=C('QUESTION_OPTS');
		$this->type_control=C('TYPE_CONTROL');
		$this->option_count=C('OPTION_COUNT');
		
		$this->assign("question_types",$this->question_types);
		$this->assign("question_opts",$this->question_opts);
		$this->assign("question_level",$this->question_level);
		$this->assign("type_control",$this->type_control);
		$this->assign("option_count",$this->option_count);
	}
    
    // 后台考题管理列表
    public function index(){

        $id=I('id',0,'intval');
        $term_id=I('term_id',0,'intval');
        $type_id=I('type_id',0,'intval');
        $ques_level=I('ques_level',0,'intval');
        $keyword=I('keyword');

        $this->assign("id",$id==0?'':$id);
		$this->assign("term_id",$term_id);
		$this->assign("type_id",$type_id);
		$this->assign("keyword",$keyword);
        
		$map=null;
		$map['a.ques_status']=0;
		if($id>0) $map['a.id']=$id;
/* 		if($term_id>0) $map['a.ques_term']=$term_id;
		if($type_id>0) $map['a.ques_type']=$type_id;		
		if($ques_level>0) $map['a.ques_level']=$ques_level;
		if(!empty($keyword)) $map['a.ques_content']=$keyword; */
		if(isset($map))$map['_logic']='AND';
        $this->_lists($map);
        $this->_getTree();

        $question_terms=array();
        $terms=$this->terms_model->select();        
        foreach ($terms as $term){
            $question_terms[$term['term_id']]=$term['name'];
        }
        
		$this->assign("question_terms",$question_terms);
        $this->display();
    }
    
    /**
     * 考试列表，用于试卷选择时使用
     */
    public function queslist(){
    
        $id=I('id',0,'intval');
        $term_id=I('term_id',0,'intval');
        $paper_type=I('paper_type',0,'intval');
        $keyword=I('keyword');
    
        $this->assign("id",$id==0?'':$id);
        $this->assign("term_id",$term_id);
        $this->assign("paper_type",$paper_type);
        $this->assign("keyword",$keyword);
    
        $map=null;
        if($id>0) $map['a.id']=$id;
        if($term_id>0) $map['a.ques_term']=$term_id;
        if($paper_type>0) $map['a.ques_type']=$paper_type;
        if(!empty($keyword)) $map['a.ques_content']=$keyword;
        if(isset($map))$map['_logic']='AND';
        $this->_lists($map);
        $this->_getTree();
    
        $question_terms=array();
        $terms=$this->terms_model->select();
        foreach ($terms as $term){
            $question_terms[$term['term_id']]=$term['name'];
        }
    
        $this->assign("question_terms",$question_terms);
        $this->display();
    }
    // 用户头像上传
    public function excel_upload(){
        $config=array(
            'rootPath' => './'.C("UPLOADPATH"),
            'savePath' => './excel/',
            'maxSize' => 512000,//500K
            'saveName'   =>    array('uniqid',''),
            'exts'       =>    array('xls', 'xlsx'),
            'autoSub'    =>    false,
        );
        $upload = new \Think\Upload($config,'Local');//先在本地裁剪
        $info=$upload->upload();
        //开始上传
        if ($info) {
            //上传成功
            //写入附件数据库信息
            $first=array_shift($info);
            //var_dump($first);
            //$file=$first['savename'];
            return $first;
            //session('avatar',$file);
            //$this->ajaxReturn(sp_ajax_return(array("file"=>$file),"上传成功！",1),"AJAX_UPLOAD");
        } else {
            return null;
            //上传失败，返回错误
            //$this->ajaxReturn(sp_ajax_return(array(),$upload->getError(),0),"AJAX_UPLOAD");
        }
    }
    
    // 题目导入
    public function import(){
        $terms = $this->terms_model->order(array("listorder"=>"asc"))->select();
        $term_id = I("get.term",0,'intval');
        $this->_getTermTree();
        $term=$this->terms_model->where(array('term_id'=>$term_id))->find();
        $this->assign("term",$term);
        $this->assign("terms",$terms);
        $this->display();
    } 
    /**
     * 导入EXCEL题库处理
     */
    public function import_post(){
        $term_id=I('term_id',0,'intval');
        $term_id||$this->error("请选择题目所属工种！");
        $user_id=get_current_admin_id();
        
        $fileinfo=$this->excel_upload();
        $file='./'.C("UPLOADPATH").$fileinfo["savepath"].$fileinfo["savename"];
        //var_dump($file);
        if(isset($file)){
            $data=import_excel($file);
            //var_dump($data);
            $excel_header=$data[1];
            
            $headconfig=array(
                "题目类型"=>array("col_index"=>0,"name"=>"ques_type","type"=>array("单选题"=>1,"是非题"=>4,"多选题"=>2)),
                "难度"=>array("col_index"=>1,"name"=>"ques_level","level"=>array("初级"=>"1","中级"=>"2","高级"=>"3")),
                "题目标题"=>array("col_index"=>2,"name"=>"ques_content"),
                "题目答案"=>array("col_index"=>3,"name"=>"answer","value"=>array("A"=>1,"B"=>2,"C"=>3,"D"=>4,"E"=>5)),
                "答案解析"=>array("col_index"=>4,"name"=>"ques_guide"),
                "选项A"=>array("col_index"=>5,"name"=>"options"),
                "选项B"=>array("col_index"=>6,"name"=>"options"),
                "选项C"=>array("col_index"=>7,"name"=>"options"),
                "选项D"=>array("col_index"=>8,"name"=>"options"),
                "选项E"=>array("col_index"=>9,"name"=>"options"),
            );
            //var_dump($data);
            $ques_data_arr=array();
            for ($i=2;$i<count($data)+1;$i++){
//                 var_dump($i);
//                 var_dump($headconfig["题目类型"]["col_index"]);
//                 var_dump($data[$i][$headconfig["题目类型"]["col_index"]]);
//                 die();
                $tmp_ques[$headconfig["题目类型"]["name"]]=$headconfig["题目类型"]["type"][$data[$i][$headconfig["题目类型"]["col_index"]]];
                $tmp_ques[$headconfig["难度"]["name"]]=$headconfig["难度"]["level"][$data[$i][$headconfig["难度"]["col_index"]]];
                $tmp_ques[$headconfig["题目标题"]["name"]]=$data[$i][$headconfig["题目标题"]["col_index"]];
                $tmp_ques[$headconfig["题目答案"]["name"]]=str_replace("E", "5",str_replace("D", "4",str_replace("C", "3",str_replace("B", "2",str_replace("A", "1",strtoupper($data[$i][$headconfig["题目答案"]["col_index"]]))))));
                $tmp_ques[$headconfig["答案解析"]["name"]]==$data[$i][$headconfig["答案解析"]["col_index"]];
                $options_arr=array();
                $tmp_option=$data[$i][$headconfig["选项A"]["col_index"]];
                if(!empty($tmp_option)){
                    $options_arr[]=$tmp_option;
                }
                $tmp_option=$data[$i][$headconfig["选项B"]["col_index"]];
                if(!empty($tmp_option)){
                    $options_arr[]=$tmp_option;
                }
                $tmp_option=$data[$i][$headconfig["选项C"]["col_index"]];
                if(!empty($tmp_option)){
                    $options_arr[]=$tmp_option;
                }
                $tmp_option=$data[$i][$headconfig["选项D"]["col_index"]];
                if(!empty($tmp_option)){
                    $options_arr[]=$tmp_option;
                }
                $tmp_option=$data[$i][$headconfig["选项E"]["col_index"]];
                if(!empty($tmp_option)){
                    $options_arr[]=$tmp_option;
                }
                $tmp_ques['option_count']=count($options_arr);
                $tmp_ques['ques_term']=$term_id;
                $tmp_ques['options']=serialize($options_arr);
                $tmp_ques['user_id']=$user_id;
                $tmp_ques['ques_source']="批量导入";
                $ques_data_arr[]=$tmp_ques;
            }
            if(count($ques_data_arr)>0){
                $ret=$this->ques_model->addAll($ques_data_arr);
                if($ret){
                    $sql="insert into cmf_ques_term_relationships(term_id,object_id) (select ques_term,id from cmf_questions a where a.id not in (select object_id from cmf_ques_term_relationships))";
                    M()->execute($sql);
                    $this->success("导入成功".count($ques_data_arr)."条！");
                }
            }
        }
        else{
            $this->error("上传失败！");
        }
    }
    
    // 文章添加
    public function add(){
        $terms = $this->terms_model->order(array("listorder"=>"asc"))->select();
        $term_id = I("get.term",0,'intval');
        $this->_getTermTree();
        $term=$this->terms_model->where(array('term_id'=>$term_id))->find();
        $this->assign("term",$term);
        $this->assign("terms",$terms);
        $this->display();
    }
    
    // 文章添加提交
    public function add_question(){
        //var_dump($_POST);die();
        if (IS_POST) {
            if(empty($_POST['ques_type'])){
                $this->error("请至少选择一个题型！");
            }
            if(empty($_POST['ques_term'])){
                $this->error("请至少选择一个分类！");
            }
            if(empty($_POST['ques_content'])){
                $this->error("请填写题干！");
            }
            
            //die(dump($_POST));

            $data['ques_term']=I("ques_term",0,'intval');
            $data['ques_type']=I("ques_type",0,'intval');
            $data['ques_level']=I("ques_level",0,'intval');
            $data['option_count']=I("option_count",0,'intval');
            $data['ques_status']=I("questions",0,'intval');
            $data['ques_guide']=I("ques_guide",0);
            $data['ques_score']=I("ques_score",0,'intval');
            $data['ques_source']=I("ques_source",0);
            $data['ques_content']=I("ques_content",0);
            $data['listorder']=I("listorder",0,'intval');
            $data['answer']=is_array(I("opts"))?implode(',',I("opts")):I("opt");
            $single_question_answer=I("single_question_answer");
            $many_question_answer=I("many_question_answer");
            $empty_question_answer=I("empty_question_answer");


            switch($data['ques_type']){
                case 1:
                case 4:
                    !$this->validateOptions($single_question_answer)&&$this->error("选项内容不能为空!");
                    $data['options']=serialize($single_question_answer);
                    break;
                case 2:
                    !$this->validateOptions($many_question_answer)&&$this->error("多选选项选项内容不能为空!");
                    $data['options']=serialize($many_question_answer);
                    break;
                case 3:
                    !$this->validateOptions($empty_question_answer)&&$this->error("填空选项内容不能为空!");
                    $data['options']=serialize($empty_question_answer);
                    break;
//                 case 4:
//                     !$this->validateOptions($empty_question_answer)&&$this->error("判断选项内容不能为空!");
//                     $data['options']=serialize($empty_question_answer);
//                     break;
                case 5:
                    $data['options']='';
                    break;
            }
            
            
            switch($data['ques_type']){
                case 1:
                    empty($data['answer'])&&$this->error("请选择单选题答案");
                    break;
                case 2:
                    empty($data['answer'])&&$this->error("请选择多选题答案");
                    break;
                case 4:
                    empty($data['answer'])&&$this->error("请选择判断题答案");
                    break;
            }
            switch($data['ques_type']){
                case 1:
                    empty($single_question_answer)&&$this->error("请填写单选问题选项内容！");
                    break;
                case 2:
                    empty($many_question_answer)&&$this->error("请填写多选问题选项内容！");
                    break;
                case 3:
                    empty($empty_question_answer)&&$this->error("请填写填空问题正确答案！");
                    break;
                case 4:
                    empty($single_question_answer)&&$this->error("请填写判断题选项！");
                    break;
            }
            

            $data['ques_type']!=5&&count($data['options'])==$data['option_count']&&$this->error("选项数目不一致!");
            
            $data['ques_modified']=date("Y-m-d H:i:s",time());
            $data['user_id']=get_current_admin_id();
            $data['ques_content']=htmlspecialchars_decode($data['ques_content']);
            $result=$this->ques_model->add($data);
            if ($result) {
                $mterm_id=$data['ques_term'];
                $this->term_relationships_model->add(array("term_id"=>intval($mterm_id),"object_id"=>$result));
                $this->success("添加成功！");
            } else {
                $this->error("添加失败！");
            }
        
        }
    }
    /**
     * 检查数据内容是否存在内数据
     * @param unknown $options
     */
    public function validateOptions($options){
        foreach ($options as $opt)
        {
            if(empty($opt))
                return false;
        }
        return true;
    }
    // 文章编辑
    public function edit(){
        $id=  I("get.id",0,'intval');
        empty($id)&&$this->error("操作错误，无效的ID！");
        
        $ques=$this->ques_model->find($id);
        $this->assign("ques",$ques);
        $this->assign("ques_options",json_encode(unserialize($ques['options'])));
        $terms = $this->terms_model->order(array("listorder"=>"asc"))->select();
        $term_id = $ques['ques_term'];

        $term=$this->terms_model->where(array('term_id'=>$term_id))->find();
        $this->assign("ques_id",$id);
        $this->_getTermTree(array($term_id));
        $this->assign("term",$term);
        $this->assign("terms",$terms);
        $this->display();
    }
    
    // 文章编辑提交
    public function edit_question(){
        if (IS_POST) {
            if(empty($_POST['ques_id'])){
                $this->error("操作错误，无效的ID！");
            }
            if(empty($_POST['ques_type'])){
                $this->error("请至少选择一个题型！");
            }
            if(empty($_POST['ques_term'])){
                $this->error("请至少选择一个分类！");
            }
            if(empty($_POST['ques_content'])){
                $this->error("请填写题干！");
            }
            $data['id']=I("ques_id");
            $data['ques_term']=I("ques_term",0,'intval');
            $data['ques_type']=I("ques_type",0,'intval');
            $data['ques_level']=I("ques_level",0,'intval');
            $data['option_count']=I("option_count",0,'intval');
            $data['ques_status']=I("questions",0,'intval');
            $data['ques_guide']=I("ques_guide",0);
            $data['ques_score']=I("ques_score",0,'intval');
            $data['ques_source']=I("ques_source",0);
            $data['ques_content']=I("ques_content",0);
            $data['listorder']=I("listorder",0,'intval');
            $data['answer']=is_array(I("opts"))?implode(',',I("opts")):I("opt");
            $single_question_answer=I("single_question_answer");
            $many_question_answer=I("many_question_answer");
            $empty_question_answer=I("empty_question_answer");


            switch($data['ques_type']){
                case 1:
                case 4:
                    !$this->validateOptions($single_question_answer)&&$this->error("选项内容不能为空!");
                    $data['options']=serialize($single_question_answer);
                    break;
                case 2:
                    !$this->validateOptions($many_question_answer)&&$this->error("多选选项选项内容不能为空!");
                    $data['options']=serialize($many_question_answer);
                    break;
                case 3:
                    !$this->validateOptions($empty_question_answer)&&$this->error("填空选项内容不能为空!");
                    $data['options']=serialize($empty_question_answer);
                    break;
//                 case 4:
//                     !$this->validateOptions($empty_question_answer)&&$this->error("判断选项内容不能为空!");
//                     $data['options']=serialize($empty_question_answer);
//                     break;
                case 5:
                    $data['options']='';
                    break;
            }
            
            
            switch($data['ques_type']){
                case 1:
                    empty($data['answer'])&&$this->error("请选择单选题答案");
                    break;
                case 2:
                    empty($data['answer'])&&$this->error("请选择多选题答案");
                    break;
                case 4:
                    empty($data['answer'])&&$this->error("请选择判断题答案");
                    break;
            }
            switch($data['ques_type']){
                case 1:
                    empty($single_question_answer)&&$this->error("请填写单选问题选项内容！");
                    break;
                case 2:
                    empty($many_question_answer)&&$this->error("请填写多选问题选项内容！");
                    break;
                case 3:
                    empty($empty_question_answer)&&$this->error("请填写填空问题正确答案！");
                    break;
                case 4:
                    empty($single_question_answer)&&$this->error("请填写判断题选项！");
                    break;
            }
            

            $data['ques_type']!=5&&count($data['options'])==$data['option_count']&&$this->error("选项数目不一致!");
            
            $data['ques_modified']=date("Y-m-d H:i:s",time());
            $data['user_id']=get_current_admin_id();
            $data['ques_content']=htmlspecialchars_decode($data['ques_content']);
            $result=$this->ques_model->save($data);
            if ($result) {
                $ques_id=$data['id'];
                $relate=$this->term_relationships_model->where("object_id=%d",$ques_id)->find();
                if($relate){
                    $mterm_id=$relate['ques_term'];
                    $this->term_relationships_model->save(array("id"=>$relate['id'],"term_id"=>intval($mterm_id),"object_id"=>$ques_id));
                    $this->success("修改成功！");
                }
                
            } else {
                $this->error("修改失败！");
            }
        
        }
    }
    // 文章排序
    public function sorts() {
        $status = parent::_sorts($this->term_relationships_model);
        if ($status) {
            $this->success("排序更新成功！");
        } else {
            $this->error("排序更新失败！");
        }
    }
    
    /**
     * 文章列表处理方法,根据不同条件显示不同的列表
     * @param array $where 查询条件
     */
    private function _lists($where=array()){
        $term_id=I('request.term_id',0,'intval');
        $type_id=I('request.type_id',0,'intval');
        $ques_level=I('request.ques_level',0,'intval');
        
        if(!empty($term_id)){
            $where['ques_term']=$term_id;
            $term=$this->ques_model->where(array('ques_term'=>$term_id))->find();
            $this->assign("term",$term);
        }
        if(!empty($type_id)){
            $where['ques_type']=$type_id;
            $this->assign("type_id",$type_id);
        }

        if(!empty($ques_level)){
            $where['ques_level']=$ques_level;
            $this->assign("ques_level",$ques_level);
        }
        $start_time=I('request.start_time');
        if(!empty($start_time)){
            $where['ques_date']=array(
                array('EGT',$start_time)
            );
        }
    
        $end_time=I('request.end_time');
        if(!empty($end_time)){
            if(empty($where['ques_date'])){
                $where['ques_date']=array();
            }
            array_push($where['ques_date'], array('ELT',$end_time));
        }
    
        $keyword=I('request.keyword');
        if(!empty($keyword)){
            $where['ques_content']=array('like',"%$keyword%");
        }
        if(isset($where))$where['_logic']='AND';
        $this->ques_model
        ->alias("a")
        ->where($where);
    
        if(!empty($term_id)){
            $this->ques_model->join("__QUES_TERM_RELATIONSHIPS__ b ON a.id = b.object_id");
        }
    
        $count=$this->ques_model->count();
        	
        $page = $this->page($count, $Think.ACTION_NAME=='queslist'?$count:20);
        	
        $this->ques_model
        ->alias("a")
        ->join("__USERS__ c ON a.user_id = c.id")
        ->where($where)
        ->limit($page->firstRow , $page->listRows)
        ->order("a.ques_date DESC");
        if(empty($term_id)){
            $this->ques_model->field('a.*,c.user_login,c.user_nicename');
        }else{
            $this->ques_model->field('a.*,c.user_login,c.user_nicename,b.listorder,b.tid');
            $this->ques_model->join("__QUES_TERM_RELATIONSHIPS__ b ON a.id = b.object_id");
        }
        $posts=$this->ques_model->select();
        //echo $this->ques_model->getLastSql();
        $this->assign("page", $page->show('Admin'));
        $this->assign("formget",array_merge($_GET,$_POST));
        $this->assign("posts",$posts);
    }
       
    // 获取文章分类树结构 select 形式
    private function _getTree(){
        $term_id=empty($_REQUEST['term_id'])?6:intval($_REQUEST['term_id']);
        $result = $this->terms_model->order(array("listorder"=>"asc"))->select();
    
        $tree = new \Tree();
        $tree->icon = array('&nbsp;&nbsp;&nbsp;│ ', '&nbsp;&nbsp;&nbsp;├─ ', '&nbsp;&nbsp;&nbsp;└─ ');
        $tree->nbsp = '&nbsp;&nbsp;&nbsp;';
        foreach ($result as $r) {
            $r['str_manage'] = '<a href="' . U("AdminTerm/add", array("parent" => $r['term_id'])) . '">添加子类</a> | <a href="' . U("AdminTerm/edit", array("id" => $r['term_id'])) . '">修改</a> | <a term="js-ajax-delete" href="' . U("AdminTerm/delete", array("id" => $r['term_id'])) . '">删除</a> ';
            $r['visit'] = "<a href='#'>访问</a>";
            $r['taxonomys'] = $this->taxonomys[$r['taxonomy']];
            $r['id']=$r['term_id'];
            $r['parentid']=$r['parent'];
            $r['selected']=$term_id==$r['term_id']?"selected":"";
            $array[] = $r;
        }
    
        $tree->init($array);
        $str="<option value='\$id' \$selected>\$spacer\$name</option>";
        $taxonomys = $tree->get_tree(0, $str);
        $this->assign("taxonomys", $taxonomys);
    }
    
    // 获取文章分类树结构
    private function _getTermTree($term=array()){
        $result = $this->terms_model->order(array("listorder"=>"asc"))->select();
    
        $tree = new \Tree();
        $tree->icon = array('&nbsp;&nbsp;&nbsp;│ ', '&nbsp;&nbsp;&nbsp;├─ ', '&nbsp;&nbsp;&nbsp;└─ ');
        $tree->nbsp = '&nbsp;&nbsp;&nbsp;';
        foreach ($result as $r) {
            $r['str_manage'] = '<a href="' . U("AdminTerm/add", array("parent" => $r['term_id'])) . '">添加子类</a> | <a href="' . U("AdminTerm/edit", array("id" => $r['term_id'])) . '">修改</a> | <a term="js-ajax-delete" href="' . U("AdminTerm/delete", array("id" => $r['term_id'])) . '">删除</a> ';
            $r['visit'] = "<a href='#'>访问</a>";
            $r['taxonomys'] = $this->taxonomys[$r['taxonomy']];
            $r['id']=$r['term_id'];
            $r['parentid']=$r['parent'];
            $r['selected']=in_array($r['term_id'], $term)?"selected":"";
            $r['checked'] =in_array($r['term_id'], $term)?"checked":"";
            $array[] = $r;
        }
    
        $tree->init($array);
        $str="<option value='\$id' \$selected>\$spacer\$name</option>";
        $taxonomys = $tree->get_tree(0, $str);
        $this->assign("taxonomys", $taxonomys);
    }
    
    // 文章删除
    public function delete(){
        if(isset($_GET['id'])){
            $id = I("get.id",0,'intval');
            if ($this->ques_model->where(array('id'=>$id))->save(array('ques_status'=>3)) !==false) {
                $this->success("删除成功！");
            } else {
                $this->error("删除失败！");
            }
        }
    
        if(isset($_POST['ids'])){
            $ids = I('post.ids/a');
            	
            if ($this->ques_model->where(array('id'=>array('in',$ids)))->save(array('ques_status'=>3))!==false) {
                $this->success("删除成功！");
            } else {
                $this->error("删除失败！");
            }
        }
    }
    
    // 文章审核
    public function check(){
        if(isset($_POST['ids']) && $_GET["check"]){
            $ids = I('post.ids/a');
            	
            if ( $this->ques_model->where(array('id'=>array('in',$ids)))->save(array('ques_status'=>1)) !== false ) {
                $this->success("审核成功！");
            } else {
                $this->error("审核失败！");
            }
        }
        if(isset($_POST['ids']) && $_GET["uncheck"]){
            $ids = I('post.ids/a');
    
            if ( $this->ques_model->where(array('id'=>array('in',$ids)))->save(array('ques_status'=>0)) !== false) {
                $this->success("取消审核成功！");
            } else {
                $this->error("取消审核失败！");
            }
        }
    }
    
    // 文章置顶
    public function top(){
        if(isset($_POST['ids']) && $_GET["top"]){
            $ids = I('post.ids/a');
            	
            if ( $this->ques_model->where(array('id'=>array('in',$ids)))->save(array('istop'=>1))!==false) {
                $this->success("置顶成功！");
            } else {
                $this->error("置顶失败！");
            }
        }
        if(isset($_POST['ids']) && $_GET["untop"]){
            $ids = I('post.ids/a');
    
            if ( $this->ques_model->where(array('id'=>array('in',$ids)))->save(array('istop'=>0))!==false) {
                $this->success("取消置顶成功！");
            } else {
                $this->error("取消置顶失败！");
            }
        }
    }
    
    // 文章推荐
    public function recommend(){
        if(isset($_POST['ids']) && $_GET["recommend"]){
            $ids = I('post.ids/a');
            	
            if ( $this->ques_model->where(array('id'=>array('in',$ids)))->save(array('recommended'=>1))!==false) {
                $this->success("推荐成功！");
            } else {
                $this->error("推荐失败！");
            }
        }
        if(isset($_POST['ids']) && $_GET["unrecommend"]){
            $ids = I('post.ids/a');
    
            if ( $this->ques_model->where(array('id'=>array('in',$ids)))->save(array('recommended'=>0))!==false) {
                $this->success("取消推荐成功！");
            } else {
                $this->error("取消推荐失败！");
            }
        }
    }
    
    // 文章批量移动
    public function move(){
        if(IS_POST){
            if(isset($_GET['ids']) && $_GET['old_term_id'] && isset($_POST['term_id'])){
                $old_term_id=I('get.old_term_id',0,'intval');
                $term_id=I('post.term_id',0,'intval');
                if($old_term_id!=$term_id){
                    $ids=explode(',', I('get.ids/s'));
                    $ids=array_map('intval', $ids);
    
                    foreach ($ids as $id){
                        $this->term_relationships_model->where(array('object_id'=>$id,'term_id'=>$old_term_id))->delete();
                        $find_relation_count=$this->term_relationships_model->where(array('object_id'=>$id,'term_id'=>$term_id))->count();
                        if($find_relation_count==0){
                            $this->term_relationships_model->add(array('object_id'=>$id,'term_id'=>$term_id));
                        }
                    }
                     
                }
                 
                $this->success("移动成功！");
            }
        }else{
            $tree = new \Tree();
            $tree->icon = array('&nbsp;&nbsp;&nbsp;│ ', '&nbsp;&nbsp;&nbsp;├─ ', '&nbsp;&nbsp;&nbsp;└─ ');
            $tree->nbsp = '&nbsp;&nbsp;&nbsp;';
            $terms = $this->ques_model->order(array("path"=>"ASC"))->select();
            $new_terms=array();
            foreach ($terms as $r) {
                $r['id']=$r['term_id'];
                $r['parentid']=$r['parent'];
                $new_terms[] = $r;
            }
            $tree->init($new_terms);
            $tree_tpl="<option value='\$id'>\$spacer\$name</option>";
            $tree=$tree->get_tree(0,$tree_tpl);
    
            $this->assign("terms_tree",$tree);
            $this->display();
        }
    }
    
    // 文章批量复制
    public function copy(){
        if(IS_POST){
            if(isset($_GET['ids']) && isset($_POST['term_id'])){
                $ids=explode(',', I('get.ids/s'));
                $ids=array_map('intval', $ids);
                $uid=sp_get_current_admin_id();
                $term_id=I('post.term_id',0,'intval');
                $term_count=$ques_model=M('Terms')->where(array('term_id'=>$term_id))->count();
                if($term_count==0){
                    $this->error('分类不存在！');
                }
                 
                $data=array();
                 
                foreach ($ids as $id){
                    $find_post=$this->ques_model->field('ques_keywords,ques_source,ques_content,ques_title,ques_excerpt,smeta')->where(array('id'=>$id))->find();
                    if($find_post){
                        $find_post['user_id']=$uid;
                        $find_post['ques_date']=date('Y-m-d H:i:s');
                        $find_post['ques_modified']=date('Y-m-d H:i:s');
                        $ques_id=$this->ques_model->add($find_post);
                        if($ques_id>0){
                            array_push($data, array('object_id'=>$ques_id,'term_id'=>$term_id));
                        }
                    }
                }
                 
                if ( $this->term_relationships_model->addAll($data) !== false) {
                    $this->success("复制成功！");
                } else {
                    $this->error("复制失败！");
                }
            }
        }else{
            $tree = new \Tree();
            $tree->icon = array('&nbsp;&nbsp;&nbsp;│ ', '&nbsp;&nbsp;&nbsp;├─ ', '&nbsp;&nbsp;&nbsp;└─ ');
            $tree->nbsp = '&nbsp;&nbsp;&nbsp;';
            $terms = $this->ques_model->order(array("path"=>"ASC"))->select();
            $new_terms=array();
            foreach ($terms as $r) {
                $r['id']=$r['term_id'];
                $r['parentid']=$r['parent'];
                $new_terms[] = $r;
            }
            $tree->init($new_terms);
            $tree_tpl="<option value='\$id'>\$spacer\$name</option>";
            $tree=$tree->get_tree(0,$tree_tpl);
    
            $this->assign("terms_tree",$tree);
            $this->display();
        }
    }
    
    // 文章回收站列表
    public function recyclebin(){
$id=I('id',0,'intval');
        $term_id=I('term_id',0,'intval');
        $type_id=I('type_id',0,'intval');
        $ques_level=I('ques_level',0,'intval');
        $keyword=I('keyword');

        $this->assign("id",$id==0?'':$id);
		$this->assign("term_id",$term_id);
		$this->assign("type_id",$type_id);
		$this->assign("keyword",$keyword);
        
		$map=null;
		if($id>0) $map['a.id']=$id;
		$map['a.ques_status']=3;
/* 		if($term_id>0) $map['a.ques_term']=$term_id;
		if($type_id>0) $map['a.ques_type']=$type_id;		
		if($ques_level>0) $map['a.ques_level']=$ques_level;
		if(!empty($keyword)) $map['a.ques_content']=$keyword; */
		if(isset($map))$map['_logic']='AND';
        $this->_lists($map);
        $this->_getTree();

        $question_terms=array();
        $terms=$this->terms_model->select();        
        foreach ($terms as $term){
            $question_terms[$term['term_id']]=$term['name'];
        }
        
		$this->assign("question_terms",$question_terms);
        $this->display();
    }
    
    // 清除已经删除的文章
    public function clean(){
        if(isset($_POST['ids'])){
            $ids = I('post.ids/a');
            $ids = array_map('intval', $ids);
            $status=$this->ques_model->where(array("id"=>array('in',$ids),'ques_status'=>3))->delete();
            $this->term_relationships_model->where(array('object_id'=>array('in',$ids)))->delete();
            	
            if ($status!==false) {
                $this->success("删除成功！");
            } else {
                $this->error("删除失败！");
            }
        }else{
            if(isset($_GET['id'])){
                $id = I("get.id",0,'intval');
                $status=$this->ques_model->where(array("id"=>$id,'ques_status'=>3))->delete();
                $this->term_relationships_model->where(array('object_id'=>$id))->delete();
    
                if ($status!==false) {
                    $this->success("删除成功！");
                } else {
                    $this->error("删除失败！");
                }
            }
        }
    }
    
    // 文章还原
    public function restore(){
        if(isset($_GET['id'])){
            $id = I("get.id",0,'intval');
            if ($this->ques_model->where(array("id"=>$id,'ques_status'=>3))->save(array("ques_status"=>"1"))) {
                $this->success("还原成功！");
            } else {
                $this->error("还原失败！");
            }
        }
    }
    
}